const express = require('express');
const router = express.Router();
const createError = require('http-errors');
const Supplier = require('../models/Supplier');

// 创建公司
router.post('/createSupplier', async (req, res, next) => {
  try {
    const { name, contact, phone, address } = req.body;

    // 参数验证
    if (!name || !contact || !phone || !address) {
      throw createError(400, '缺少必要参数');
    }

    const supplier = await Supplier.create({
      name,
      contact,
      phone,
      address
    });

    res.json(supplier);

  } catch (error) {
    next(error);
  }
});

// 获取公司列表
router.get('/getSupplierList', async (req, res, next) => {
  try {
    // 获取分页参数
    const { page, size, offset } = req.getPaginationParams();

    // 查询数据
    const { count, rows } = await Supplier.findAndCountAll({
      attributes: ['id', 'name', 'contact', 'phone', 'address', 'createdAt', 'updatedAt'],
      offset,
      limit: size,
      order: [['createdAt', 'DESC']]  // 按创建时间倒序
    });

    // 返回分页数据
    res.paginate(rows, {
      total: count,
      page,
      size
    });

  } catch (error) {
    next(error);
  }
});

// 获取单个公司
router.get('/:id', async (req, res, next) => {
  try {
    const supplier = await Supplier.findByPk(req.params.id);

    if (!supplier) {
      throw createError(404, '公司不存在');
    }

    res.json(supplier);

  } catch (error) {
    next(error);
  }
});

// 更新公司
router.put('/:id', async (req, res, next) => {
  try {
    const { name, contact, phone, address } = req.body;
    const supplier = await Supplier.findByPk(req.params.id);

    if (!supplier) {
      throw createError(404, '公司不存在');
    }

    await supplier.update({
      name: name || supplier.name,
      contact: contact || supplier.contact,
      phone: phone || supplier.phone,
      address: address || supplier.address
    });

    res.json(supplier);

  } catch (error) {
    next(error);
  }
});

// 删除公司
router.delete('/:id', async (req, res, next) => {
  try {
    const supplier = await Supplier.findByPk(req.params.id);

    if (!supplier) {
      throw createError(404, '公司不存在');
    }

    await supplier.destroy();

    res.json({ message: '删除成功' });

  } catch (error) {
    next(error);
  }
});

module.exports = router;
